package com.workcenter.app;

import java.util.ArrayList;
import java.util.Date;

import com.ppcodes.core.data.DXml;
import com.ppcodes.core.data.DXml.FieldList;
import com.ppcodes.core.utils.UtiDialogsFactory;
import com.workcenter.base.UIBase;
import com.workcenter.controls.AdpLV_RepairsInfo;
import com.workcenter.entity.NetClient;
import com.workcenter.entity.PubConst;
import com.workcenter.entity.Session;
import com.workcenter.entity.UrlParams;
import com.workcenter.entity.model.ERepairsInfo;
import com.workcenter.entity.model.ESearchCondition;

import android.os.Bundle;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class UIMain extends UIBase
{
   private ImageView imgRefresh;
   private ImageView imgAdd;
   private ImageView imgFilter;
   private ImageView imgStatistics;

   private TextView txtInfo;

   private ListView listView;

   private void InitControls()
   {
	  imgRefresh = (ImageView) findViewById(R.id.imgRefresh_toptoolbar);
	  imgRefresh.setOnClickListener(new View.OnClickListener()
	  {
		 @Override
		 public void onClick(View v)
		 {
			CleanList();
			executeAsyncTask(PubConst.TaskName.Main_LoadListData);
		 }
	  });
	  imgFilter = (ImageView) findViewById(R.id.imgFilter_toptoolbar);
	  imgFilter.setOnClickListener(new View.OnClickListener()
	  {
		 @Override
		 public void onClick(View v)
		 {
			Intent intent = new Intent();
			intent.setClass(UIMain.this, UIFilter.class);
			startActivityForResult(intent, PubConst.ActivityCode.UIFilter);
		 }
	  });
	  imgAdd = (ImageView) findViewById(R.id.imgAdd_toptoolbar);
	  imgAdd.setOnClickListener(new View.OnClickListener()
	  {
		 @Override
		 public void onClick(View v)
		 {
			Intent intent = new Intent();
			intent.setClass(UIMain.this, UINewRepairs.class);
			startActivityForResult(intent, PubConst.ActivityCode.UINewRepairs);
		 }
	  });
	  imgStatistics = (ImageView) findViewById(R.id.imgStatistics_toptoolbar);
	  imgStatistics.setOnClickListener(new View.OnClickListener()
	  {
		 @Override
		 public void onClick(View v)
		 {
			Intent intent = new Intent();
			intent.setClass(UIMain.this, UIStatistics.class);
			startActivity(intent);
		 }
	  });
	  txtInfo = (TextView) findViewById(R.id.txtInfo_topinfobar);
	  txtInfo.setText(String.format("欢迎登陆%s!", Session.getInstance().getUserInfo().getUserName()));

	  listView = (ListView) findViewById(R.id.listView_main);
	  listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
	  {
		 @Override
		 public void onItemClick(AdapterView<?> arg0, View item, int position, long arg3)
		 {
			Intent intent = new Intent();
			intent.setClass(UIMain.this, UIDetails.class);
			intent.putExtra(PubConst.Intent_Key.REPAIRS_ID, String.valueOf(((ERepairsInfo) listView.getAdapter().getItem(position)).getRepairsId()));
			intent.putExtra(PubConst.Intent_Key.PROGRESS, ((ERepairsInfo) listView.getAdapter().getItem(position)).getProgress());
			startActivity(intent);
		 }
	  });
   }

   private void CleanList()
   {
	  listView.setAdapter(null);
   }

   private void GetListData(Object result)
   {
	  try
	  {
		 if (result != null)
		 {
			DXml data = (DXml) result;
			if (data.getHead().GetFieldValue("RspCode").equals(UrlParams.SuccessCode))
			{
			   ArrayList<ERepairsInfo> list = new ArrayList<ERepairsInfo>();
			   ERepairsInfo rInfo = null;
			   int size = data.getBody().getChilds().length;
			   for (int i = 0; i < size; i++)
			   {
				  FieldList fieldList = data.getBody().GetFieldList(i);

				  rInfo = new ERepairsInfo();
				  rInfo.setRepairsId(fieldList.GetFieldValue("RepairsId"));
				  rInfo.setCustomerName(fieldList.GetFieldValue("CustomerName"));
				  rInfo.setDiagnosis(fieldList.GetFieldValue("Diagnosis"));
				  rInfo.setInstrument(fieldList.GetFieldValue("Instrument"));
				  rInfo.setProgress(fieldList.GetFieldValue("Progress"));

				  list.add(rInfo);
			   }

			   AdpLV_RepairsInfo adp = new AdpLV_RepairsInfo(list, UIMain.this);
			   listView.setAdapter(adp);
			}
			else
			{
			   UtiDialogsFactory.getInstance().ShowToastInfoShort(UIMain.this, data.getHead().GetFieldValue("RspMsg"));
			}
		 }
		 else
		 {
			UtiDialogsFactory.getInstance().ShowToastInfoShort(UIMain.this, getString(R.string.dialog_server_failed));
		 }
	  }
	  catch (Exception e)
	  {
		 if (Session.getInstance().IsDEBUG())
		 {
			Log.e("ERROR", "UIMain_GetListData(result) ", e);
		 }
	  }
   }

   @Override
   public void onCreate(Bundle savedInstanceState)
   {
	  super.onCreate(savedInstanceState);
	  setContentView(R.layout.main);
	  InitControls();

	  executeAsyncTask(PubConst.TaskName.Main_LoadListData);

   }

   @Override
   public boolean onKeyDown(int keyCode, KeyEvent event)
   {
	  if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
	  {
		 UtiDialogsFactory.getInstance().ShowOKCancelAlertDialog(UIMain.this, getString(R.string.dialog_tips), getString(R.string.dialog_are_you_sure_exit), new DialogInterface.OnClickListener()
		 {
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
			   dialog.dismiss();
			   System.exit(0);
			}
		 });
	  }
	  return false;
   }

   @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data)
   {
	  if (requestCode == PubConst.ActivityCode.UINewRepairs)
	  {
		 if (resultCode == Activity.RESULT_OK)
		 {
			CleanList();
			executeAsyncTask(PubConst.TaskName.Main_LoadListData);
		 }
	  }
	  else if (requestCode == PubConst.ActivityCode.UIFilter)
	  {
		 if (resultCode == Activity.RESULT_OK)
		 {
			CleanList();
			executeAsyncTask(PubConst.TaskName.Main_LoadSearchData);
		 }
	  }
   }

   
   
   @Override
   protected void onResume()
   {
	  super.onResume();
	  RefreshNum();
   }

   private void RefreshNum()
   {
	  try
	  {
		 if (txtInfo != null)
		 {
			txtInfo.setText(String.format("欢迎登陆%s! 找到%s个报修单", Session.getInstance().getUserInfo().getUserName(), String.valueOf(listView.getAdapter()==null?0:listView.getAdapter().getCount())));
		 }
	  }
	  catch (Exception e)
	  {
		 if (Session.getInstance().IsDEBUG())
		 {
			Log.e("ERROR", "UIMain_RefreshNum() ", e);
		 }
	  }
   }

   @Override
   public void onAsyncTaskStart(String taskName, Object[] params)
   {
	  if (taskName.equals(PubConst.TaskName.Main_LoadListData) || taskName.equals(PubConst.TaskName.Main_LoadSearchData))
	  {
		 UtiDialogsFactory.getInstance().ShowLoadingDialogNoTitle(UIMain.this, getString(R.string.dialog_loading));
	  }
   }

   @Override
   public Object onAsyncTaskInBackground(String taskName, Object[] params) throws Exception
   {
	  try
	  {
		 if (taskName != null && taskName.equals(PubConst.TaskName.Main_LoadListData))
		 {
//			Date time = new Date();
//			String monthS = String.valueOf(time.getMonth() + 1);
//			String dayS = String.valueOf(time.getDate());
//			String todayDate = String.format("%s-%s-%s", String.valueOf(time.getYear() + 1900), monthS.length() == 1 ? ("0" + monthS) : monthS, dayS.length() == 1 ? ("0" + dayS) : dayS);
//			return NetClient.SearchRepairsList(new ESearchCondition("", "", todayDate, todayDate, "全部"));
			return NetClient.GetToadyRepairsList(Session.getInstance().getUserInfo().getUserName());
		 }
		 if (taskName != null && taskName.equals(PubConst.TaskName.Main_LoadSearchData))
		 {
			return NetClient.SearchRepairsList(Session.getInstance().getSearchCondition());
		 }
	  }
	  catch (Exception e)
	  {
		 if (Session.getInstance().IsDEBUG())
		 {
			Log.e("ERROR", "UIMain_onAsyncTaskInBackground(taskName, params) ", e);
		 }
	  }
	  return null;
   }

   @Override
   public void onAsyncTaskEnd(String taskId, String taskName, Object[] params, Object result)
   {
	  try
	  {
		 UtiDialogsFactory.getInstance().DismissLoadingDialog();
		 if (taskName.equals(PubConst.TaskName.Main_LoadListData))
		 {
			GetListData(result);
			RefreshNum();
		 }
		 if (taskName.equals(PubConst.TaskName.Main_LoadSearchData))
		 {
			GetListData(result);
			RefreshNum();
	     }
	  }
	  catch (Exception e)
	  {
		 UtiDialogsFactory.getInstance().DismissLoadingDialog();
		 UtiDialogsFactory.getInstance().ShowToastInfoShort(UIMain.this, getString(R.string.dialog_server_failed));
		 if (Session.getInstance().IsDEBUG())
		 {
			Log.e("ERROR", "UIMain_onAsyncTaskEnd(taskId, taskName, params, result) ", e);
		 }
	  }
   }

}
